#include "State.h"

#include <QDebug>
#include <QFile>
#include <QTextStream>
#include <QApplication>
#include <Translator.h>

#include "Player.h"

State::State(const QString& name, QGraphicsScene* scene) : m_name(name), m_img(QApplication::applicationDirPath () + "/Ress/" + name + ".png"), m_player(NULL), m_scene(scene)
{
    m_flag = false;
    m_gpx = NULL;
    m_troops = 0;
    QFile file (QApplication::applicationDirPath () + "/Ress/" + name + ".cfg");
    if(!file.open(QIODevice::ReadOnly | QIODevice::Text | QIODevice::Truncate))
        qDebug() << "Erreur critique : impossible d'ouvrir le fichier \"" << QApplication::applicationDirPath () << "/Ress/" << name << ".cfg\"";

    m_name = file.readLine();
    m_name.resize(m_name.size()-1);
    m_continent = file.readLine();
    m_continent.resize(m_continent.size()-1);
    QString coord = file.readLine();
    coord.resize(coord.size()-1);
    m_textCoord.rx() = coord.section(' ', 0, 0).toInt();
    m_textCoord.ry() = coord.section(' ', 1, 1).toInt();
    while(!file.atEnd())
    {
        QString t = file.readLine();
        if(t.isEmpty() || t.size() == 1)
            continue;
        if(t.right(1) == "\n")
            t.resize(t.size()-1);
        m_connexions.append(t);
    }

    file.close();

    for(int x = 0; x < m_img.width(); ++x)
        for(int y = 0; y < m_img.height(); ++y)
           if(qAlpha(m_img.pixel(x, y)) != 0)
            {
                m_img.setPixel(x, y, 1);
            }

    m_text = new QGraphicsSimpleTextItem(QString::number(m_troops));
    m_text->setPos(m_textCoord);
    refresh();
}

void State::setPlayer(Player* player)
{
    if(m_player != NULL)
        m_player->removeState(this);

    m_player = player;
    m_player->addState(this);
    refresh();
}

QString State::trName() const
{
    return getTranslator()->translate(m_name);
}

QString State::trContinent() const
{
    return getTranslator()->translate(m_continent);
}

bool State::isInState(const QPoint& point) const
{
    if(point.x() < 0 || point.y() < 0 || point.x() > m_img.width() || point.y() > m_img.height())
        return false;

    return qAlpha(m_img.pixel(point)) != 0;
}

void State::refresh()
{
    m_text->setText(QString::number(m_troops));

    QColor color (125, 125, 125);
    if(m_player != NULL)
    {
        color = m_player->color();
    }
    QVector<QRgb> tbl;
    tbl.append(qRgba(0, 0, 0, 0));
    tbl.append(color.rgb());
    m_img.setColorTable(tbl);
    m_img.setColor(1, color.rgb());

    if(m_gpx != NULL)
        m_scene->removeItem(m_gpx);

    m_px = QPixmap::fromImage(m_img);
    m_gpx = m_scene->addPixmap(m_px);

    if(m_text != NULL)
        m_text->setParentItem(m_gpx);
}
